import { defineStore } from 'pinia'
import { UserService } from '../services';
import { CacheService } from '@/utils/cache'

export const userStore = defineStore('userStore', {
	state: () => ({
		// 用户信息
		user: {
			id: '',
			username: '',
			avatar: ''
		},
		// 权限列表
		authorityList: [],
		// 登录token
		token: CacheService.getToken(),
		tokenName: CacheService.getTokenName()
	}),
	actions: {
		setUser(userInfo: any) {
			this.user = userInfo
		},
		setToken(val: any, tokenName: any) {
			this.token = val
			this.tokenName = tokenName
			CacheService.setToken(val)
			CacheService.setTokenName(tokenName)
		},
		// 用户登录
		async loginAction(loginForm: any) {
			const res: any = await UserService.useLogin(loginForm)
			this.setToken(res.tokenValue, res.tokenName)
			return Promise.resolve()
		},
		// 获取用户信息
		async getUserInfoAction() {
			const userInfo = await UserService.getOauthUserInfo()
			this.setUser(userInfo)
		},
		// 获取全部权限（页面是否显示）列表
		async getAuthorityListAction() {
			const list = await UserService.useAuthorityList()
			this.authorityList = list || []
		},
		// 用户退出
		async logoutAction() {
			//后台退出
			await UserService.useLogout()
			//移除前端用户信息
			this.user = {
				id: '',
				username: '',
				avatar: ''
			}
			//移除前端权限
			this.authorityList = []

			// 移除 token tokenName
			this.setToken(null, null)
		}
	}
})
